<route lang="json5">
{
  style: { navigationBarTitleText: 'Register' },
}
</route>
<template>
  <view class="register-container">
    <view class="logo-box">
      <image src="/static/logo.png" mode="aspectFit" class="logo" />
    </view>

    <wd-form ref="formRef" :model="formData" :rules="rules">
      <wd-form-item label="Username" prop="username">
        <wd-input v-model="formData.username" placeholder="Enter username" clearable />
      </wd-form-item>

      <wd-form-item label="Email" prop="email">
        <wd-input v-model="formData.email" placeholder="Enter email address" clearable />
      </wd-form-item>

      <wd-form-item label="Password" prop="password">
        <wd-input
          v-model="formData.password"
          type="password"
          placeholder="Enter password"
          clearable
        />
      </wd-form-item>

      <wd-form-item label="Confirm Password" prop="confirmPassword">
        <wd-input
          v-model="formData.confirmPassword"
          type="password"
          placeholder="Confirm your password"
          clearable
        />
      </wd-form-item>

      <wd-form-item label="Verification Code" prop="validCode">
        <view class="captcha-container">
          <wd-input v-model="formData.validCode" placeholder="Enter verification code" />
          <image :src="captchaImage" @click="refreshCaptcha" class="captcha-image" />
        </view>
      </wd-form-item>

      <view class="submit-btn">
        <wd-button type="primary" block @click="handleRegister">Register</wd-button>
      </view>
    </wd-form>

    <view class="action-row">
      <text class="login-link" @click="goToLogin">Already have an account? Login now</text>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { register, getPicCaptcha } from '@/service/user'
import { encryptPassword } from '@/utils/sm2'

const formRef = ref()
const captchaImage = ref('')
const validCodeReqNo = ref('')

const formData = reactive({
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
  validCode: '',
})

const rules = {
  username: [
    { required: true, message: 'Please enter username' },
    { min: 3, message: 'Username must be at least 3 characters' },
  ],
  email: [
    { required: true, message: 'Please enter email address' },
    {
      pattern: /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/,
      message: 'Please enter a valid email address',
    },
  ],
  password: [
    { required: true, message: 'Please enter password' },
    { min: 6, message: 'Password must be at least 6 characters' },
  ],
  confirmPassword: [
    { required: true, message: 'Please confirm your password' },
    {
      validator: (value: string) => value === formData.password,
      message: 'Passwords do not match',
    },
  ],
  validCode: [{ required: true, message: 'Please enter verification code' }],
}

// 获取验证码
const refreshCaptcha = async () => {
  try {
    const res = await getPicCaptcha()
    captchaImage.value = res.data.validCodeBase64
    validCodeReqNo.value = res.data.validCodeReqNo
  } catch (error) {
    uni.showToast({
      title: 'Failed to get verification code',
      icon: 'none',
    })
  }
}

// 处理注册
const handleRegister = () => {
  formRef.value
    .validate()
    .then(async () => {
      try {
        const encryptedPassword = encryptPassword(formData.password)

        const res = await register(
          formData.username,
          encryptedPassword,
          formData.email,
          'PC',
          formData.validCode,
          validCodeReqNo.value,
        )

        if (res.code !== 200) {
          uni.showToast({
            title: res.msg,
            icon: 'none',
          })
          return
        }

        // 注册成功
        uni.showToast({
          title: 'Registration successful',
          icon: 'success',
        })

        setTimeout(() => {
          goToLogin()
        }, 1500)
      } catch (error: any) {
        refreshCaptcha() // 刷新验证码

        // 显示具体的错误信息
        uni.showToast({
          title: error.data?.msg || 'Registration failed, please try again',
          icon: 'none',
          duration: 2000,
        })

        // 如果是验证码错误，清空验证码输入
        if (error.data?.msg?.includes('验证码')) {
          formData.validCode = ''
        }

        // 如果是用户名已存在，清空用户名输入
        if (error.data?.msg?.includes('用户已存在')) {
          formData.username = ''
        }

        // 处理邮箱相关错误
        if (error.data?.msg?.includes('邮箱')) {
          formData.email = ''
        }
      }
    })
    .catch((errors) => {
      // 表单验证失败的错误提示
      uni.showToast({
        title: Object.values(errors)[0]?.[0]?.message || 'Please check your input',
        icon: 'none',
        duration: 2000,
      })
    })
}

const goToLogin = () => {
  uni.navigateTo({
    url: '/pages/my/login',
  })
}

onMounted(() => {
  refreshCaptcha()
})
</script>

<style lang="scss">
.register-container {
  padding: 40rpx;

  // 复用登录页面的样式
  .logo-box {
    display: flex;
    justify-content: center;
    margin: 60rpx 0;

    .logo {
      width: 200rpx;
      height: 200rpx;
    }
  }

  .submit-btn {
    margin-top: 40rpx;
  }

  .captcha-container {
    display: flex;
    gap: 20rpx;
    align-items: center;

    .captcha-image {
      width: 200rpx;
      height: 80rpx;
    }
  }

  .action-row {
    margin-top: 30rpx;
    text-align: center;

    .login-link {
      font-size: 28rpx;
      color: #0083ff;
    }
  }
}
</style>
